<?php

namespace app\admin\model;

use Symfony\Component\VarDumper\Cloner\Data;
use think\facade\Db;
use think\Model;

class User extends Model
{
    protected $id;
    // 设置字段信息
    protected $readonly = ['username'];
    public function article()
    {
        return $this->hasMany(Article::class, 'user_id', 'id');
    }
    public function comments()
    {
        return $this->hasMany(Comment::class, 'user_id', 'id');
    }
    public function collect()
    {
        return $this->hasMany(Collect::class, 'user_id', 'id');
    }
    public function searchUserNameAttr($query, $value, $data)
    {
        $query->where('username', 'like', '%' . $value . '%');
    }

    public function searchCreateTimeAttr($query, $value, $data)
    {
        $query->whereBetweenTime('create_time', $value[0], $value[1]);
    }
    /** 
     * @param array param -- limit和搜索相关参数
     */
    static public function list($param = [])
    {
        $limit = !array_key_exists('limit', $param) ? '10' : $param['limit'];
        if ($param['type'] == 'search') {
            $username = @$param['username'];
            $begin_time = @$param['begin_time'];
            $end_time = @$param['end_time'];
            if (empty($begin_time) && empty($end_time)) {
                $list = self::where('username', 'like', '%'. $username . '%')->order('status desc,id asc')->paginate($limit);
            } else {
                $list = self::withSearch(['username', 'create_time'], [
                    'username'            =>      $username,
                    'create_time'    =>    [$begin_time, $end_time],
                ])->order('status desc,id asc')->paginate($limit);
            }
        } else {
            $list = self::order('status desc,id asc')->paginate($limit);
        }
        foreach ($list as $k => $v) {
            $desc = '';
            if ($v && $v->role) {
                $desc = Role::getRoleName($v->role);
            }
            $list[$k]['role'] = substr($desc, 0, strlen($desc) - 1) == '' ? '普通vip' : substr($desc, 0, strlen($desc) - 1);
        }
        $arr = [
            'code' => 0,
            'count' => $list->total(),
            'msg' => '',
            'data' => $list
        ];
        return json($arr);
    }

    static public function userReg()
    {
        $list = self::column('create_time');
        $data = [];
        for ($i = 1; $i <= 7; $i++) {
            $j = 0;
            foreach ($list as $k => $v) {
                $today = date('w', time());
                $t = ($today == 0 ? 7 : $today) - $i;
                if($t == 0)
                {
                    $t = time();
                }else if($t > 0){
                    $t = strtotime(date('Y-m-d',strtotime("-$t day")));
                }else{
                    $t = 0;
                }
                if (date('Y-m-d',$t) == date('Y-m-d', $v)) {
                    $j++;
                }else if($t == 0){
                    $j = 0;
                }
            }
            $data[$i] = $j;
        }
        $data = implode(',', $data);
        $data = '[' . $data . ']';
        return $data;
    }

    // 个人信息
    public function profile($id)
    {
        $data = [
            'profile' => $this->field('id , username ,nickname ,head_icon , email ,login_time ,signature ,score')->where('id', $id)->find()->toArray(),
            'articleCount' => $this->find($id)->article()->count(),
            'commentCount' => $this->find($id)->comments()->count()
        ];
        return $data;
    }
    // 删除用户 及其用户文章评论等内容
    public function del($id)
    {
        $isHas = $this->findOrEmpty($id)->isEmpty();
        if ($isHas) return error("不存在用户[$id]");
        else {
            $list = User::with(['comments' => function ($query) {
                $query->field('id,user_id');
            }, 'article' => function ($query) {
                $query->field('id,user_id');
            }, 'collect' => function ($query) {
                $query->field('id,user_id');
            }])->find($id);
            // 文章另外删除， 因为需要考虑删除图片
            foreach ($list->article as $m => $n) {
                (new Article)->del($n->id);
            }
            // 删除签到数据
            Db::name('sign')->where('user_id',$id)->delete();
            $res = $list->together(['comments', 'collect'])->delete();
            if ($res) return success();
            else return error();
        }
    }
}
